package com.laps.DB;

import com.laps.vox.Image;
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class imageDB extends SQLiteOpenHelper {

	private static final String NAME_DB = "Image";
	private static final int VERSAO = 1;
	/* */
	private static final String LOG_TAG = "Image";
	private static Context context;
	private static final String[] COLS = {"ID", "Nome", "Posicao",
		"Texto", "Imagem", "Tipo"};
	
	public imageDB(Context context) {
		super(context, NAME_DB, null, VERSAO);
		this.context = context;
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		String[] SQL = context.getString(com.laps.vox.R.string.onCreate)
				.split("\n");
		db.beginTransaction();
		try{
			for( String s : SQL ){
				if (s.trim().length()>0)
					db.execSQL(s);
			}
			db.setTransactionSuccessful();
		}
		catch(SQLException e){
			Log.e("Erro ao criar as tabelas e testar os dados", e.toString());
		}
		finally{
			 db.endTransaction();
		}
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		String[] SQL = context.getString(com.laps.vox.R.string.onUpgrade).split("\n");
		db.beginTransaction();
		
		try{
			for( String s : SQL ){
				if (s.trim().length()>0)
					db.execSQL(s);
			}
			db.setTransactionSuccessful();
		}
		catch(SQLException e){
			Log.e("Erro ao atualizar as tabelas e testar os dados", e.toString());
			throw e;
		}
		finally{
			 db.endTransaction();
		}
		onCreate(db);
	}
	
	public List<Image> getLista(){
		List<Image> imagens = new ArrayList<Image>();
		
		Cursor c = getWritableDatabase().query(LOG_TAG, COLS, null, null, null, null, null);
		
		while(c.moveToNext()){
			Image image = new Image();
			image = toImage(c);
			imagens.add(image);
		}
		c.close();
		return imagens;
	}
	
	
	
	public Image toImage(Cursor c){
		Image image = new Image();		
		image.setID(c.getInt(0));
		image.setNome(c.getString(1));
		image.setPosicao(c.getInt(2));
		image.setTexto(c.getString(3));
		image.setImagem(c.getString(4));
		image.setTipo(c.getInt(5) > 0);
		
		return image;	
	}
	
	public ContentValues toValues(Image image){
		ContentValues Novo = new ContentValues();
		Novo.put("nome", image.getNome());
		Novo.put("posicao", image.getPosicao());
		Novo.put("texto", image.getTexto());
		Novo.put("imagem", image.getImagem());
		
		return Novo;	
	}
	
	public void inserir(Image nova){
		ContentValues values = toValues(nova);
		getWritableDatabase().insert(LOG_TAG,null,values);
	}
}
